package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.DaEMaskApisUtil;
import com.block.datapush.service.apipush.utils.HaoHanYouJieSsqUtil;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantThirdBaseInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 *  大鹅钱包(掩码全流程)
 */
@Service
public class DaEApiSMaskPushService implements IPushApiService, IPushApi2Service {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("maskPhone", memberSourceInfo.getMobile().substring(0,8));
        //paramMap.put("md5Phone", memberSourceInfo.getMobileMd5());
        paramMap.put("userIp", memberSourceInfo.getReqIp());
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", "1");
        }else {
            paramMap.put("sex", "0");
        }
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("cityName",city);
        paramMap.put("loan_amount", DaEMaskApisUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("huabei",DaEMaskApisUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("jdQuota",DaEMaskApisUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("accumulation",DaEMaskApisUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("socialSecurity",DaEMaskApisUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("overdueSituation",DaEMaskApisUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("insurance",DaEMaskApisUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("house",DaEMaskApisUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("sesameSeed",DaEMaskApisUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("car",DaEMaskApisUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("profession",DaEMaskApisUtil.getJob(memberSourceInfo.getGongzuo()));

        String encryptData = DaEMaskApisUtil.encryptAES(JSON.toJSONString(paramMap), pushApiKeyParam.getApiSecret());
        HashMap<String, Object> bizMap = new HashMap<>();
        bizMap.put("encryptData", encryptData);
        bizMap.put("channelCode",pushApiKeyParam.getApiCode());

        log.info("【大鹅钱包掩码全流程分润】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【大鹅钱包掩码全流程分润】撞库结束【infoId】{}【infoName】{}【result】{}",pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("code");
        String respMsg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(respCode));
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (!StrUtil.equals(respCode, "200")) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }

        // 撞库成功之后，商户的机构数据存储
        JSONObject data = resultObject.getJSONObject("data");
        String productName = data.getString("exhibitionName");
        String serialNo = data.getString("traceId");
        String companyName = data.getString("productName");


        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        JSONObject infoObject = new JSONObject();
        infoObject.put("orderNo",serialNo);
        infoObject.put("productId",serialNo);
        infoObject.put("productName",productName);
        infoObject.put("companyName",companyName);
        infoObject.put("companyLogo","https://anyirong-1325413174.cos.ap-nanjing.myqcloud.com/merchantlogo/0015663f7c1b486e89ec9cf903547cb5dae.png");
        infoObject.put("maxLoanAmount","200000");
        infoObject.put("maxLoanRate","24");
        infoObject.put("minLoanRate","1");
        infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("protocalName", productName);
        jsonObject.put("protocalUrl", "暂无协议地址");
        jsonArray.add(jsonObject);
        infoObject.put("protocalList",jsonArray);
        thirdInfoDTO.setInfoObject(infoObject);
        JSONArray md5List = data.getJSONArray("hitPhoneList");
        String mobileMd5 = memberSourceInfo.getMobileMd5();
        if(MobileMd5IsInListUtils.isMobileMd5InList(md5List,mobileMd5)){
            //如果存在
            pushApiResult.setPushSuccess(false);
            pushApiResult.setCode(respCode+ "|" + "500");
            pushApiResult.setMessage(respMsg + "|" + mobileMd5 +"已存在");
            return pushApiResult;
        }

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
            BigDecimal price = data.getBigDecimal("price");//下游返回分润前价格
            if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceLeft = typeRate.divide(price,2, RoundingMode.HALF_UP);//分润后价格
            pushApiResult.setPrice(priceLeft);
            pushApiResult.setPriceRight(price);

        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save){
            pushApiResult.setPushSuccess(true);
            pushApiResult.setOutOrderNo(serialNo);
            extJson.put("traceId", serialNo);
        }else{
            pushApiResult.setMessage("保存撞库数据失败");
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        Map<String, Object> paramMap = new HashMap<>();
        String traceId = extJson.getString("traceId");
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("userPhone", memberSourceInfo.getMobile());
        paramMap.put("userIp", memberSourceInfo.getReqIp());
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", "1");
        }else {
            paramMap.put("sex", "0");
        }
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("cityName",city);
        paramMap.put("loan_amount", DaEMaskApisUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("huabei",DaEMaskApisUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("jdQuota",DaEMaskApisUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("accumulation",DaEMaskApisUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("socialSecurity",DaEMaskApisUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("overdueSituation",DaEMaskApisUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("insurance",DaEMaskApisUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("house",DaEMaskApisUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("sesameSeed",DaEMaskApisUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("car",DaEMaskApisUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("profession",DaEMaskApisUtil.getJob(memberSourceInfo.getGongzuo()));
        paramMap.put("traceId",traceId);

        String encryptData = DaEMaskApisUtil.encryptAES(JSON.toJSONString(paramMap), pushApiKeyParam.getApiSecret());
        HashMap<String, Object> bizMap = new HashMap<>();
        bizMap.put("encryptData", encryptData);
        bizMap.put("channelCode",pushApiKeyParam.getApiCode());

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        log.info("【大鹅钱包掩码全流程分润】导单开始【infoId】{}【infoName】{}【queryUrl】{}【bizMap】{}【paramMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【大鹅钱包掩码全流程分润】导单结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("code");
        String respMsg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(respCode));
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(respCode));
        thirdInfoDTO.setRetMsg(respMsg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals(respCode, "200")) {
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);

        if (StrUtil.equals(respCode, "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        Map<String, Object> paramMap = new HashMap<>();
        String mobileMask = memberSourceInfo.getMobileMask();
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("maskPhone", mobileMask);
        paramMap.put("md5Phone", memberSourceInfo.getMobileMd5());
        paramMap.put("userIp", memberSourceInfo.getReqIp());
        paramMap.put("age", String.valueOf(memberSourceInfo.getAge()));
        if (memberSourceInfo.getSex() == 1) {
            paramMap.put("sex", "1");
        } else {
            paramMap.put("sex", "0");
        }
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        paramMap.put("province", memberSourceInfo.getProvince());
        paramMap.put("cityName", city);
        paramMap.put("loan_amount", DaEMaskApisUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("huabei", DaEMaskApisUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("jdQuota", DaEMaskApisUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("accumulation", DaEMaskApisUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("socialSecurity", DaEMaskApisUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("overdueSituation", DaEMaskApisUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("insurance", DaEMaskApisUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("house", DaEMaskApisUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("sesameSeed", DaEMaskApisUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("car", DaEMaskApisUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("profession", DaEMaskApisUtil.getJob(memberSourceInfo.getGongzuo()));

        String encryptData = DaEMaskApisUtil.encryptAES(JSON.toJSONString(paramMap), pushApiKeyParam.getApiSecret());
        HashMap<String, Object> bizMap = new HashMap<>();
        bizMap.put("encryptData", encryptData);
        bizMap.put("channelCode", pushApiKeyParam.getApiCode());

        log.info("【大鹅钱包掩码全流程分润】 掩码撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【大鹅钱包掩码全流程分润】掩码撞库结束【infoId】{}【infoName】{}【result】{}", pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("code");
        String respMsg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(respCode));
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (!StrUtil.equals(respCode, "200")) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }

        // 撞库成功之后，商户的机构数据存储
        JSONObject data = resultObject.getJSONObject("data");
        String productName = data.getString("exhibitionName");
        String serialNo = data.getString("traceId");
        String companyName = data.getString("productName");
        JSONArray md5List = data.getJSONArray("hitPhoneList");
        pushApiResult.setMd5List(md5List);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        JSONObject infoObject = new JSONObject();
        infoObject.put("orderNo",serialNo);
        infoObject.put("productId",serialNo);
        infoObject.put("productName",productName);
        infoObject.put("companyName",companyName);
        infoObject.put("companyLogo", "https://anyirong-1325413174.cos.ap-nanjing.myqcloud.com/merchantlogo/0015663f7c1b486e89ec9cf903547cb5dae.png");
        infoObject.put("maxLoanAmount", "200000");
        infoObject.put("maxLoanRate", "24");
        infoObject.put("minLoanRate", "1");
        infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("protocalName", productName);
        jsonObject.put("protocalUrl", "暂无协议地址");
        jsonArray.add(jsonObject);
        infoObject.put("protocalList", jsonArray);
        thirdInfoDTO.setInfoObject(infoObject);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)) {
            BigDecimal price = data.getBigDecimal("price");//下游返回分润前价格
            if (price == null || price.compareTo(new BigDecimal(0.00)) == -1) {
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceLeft = typeRate.divide(price);//分润后价格
            pushApiResult.setPrice(priceLeft);
            pushApiResult.setPriceRight(price);

        }
        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setOutOrderNo(serialNo);
            extJson.put("traceId", serialNo);
        } else {
            pushApiResult.setMessage("保存撞库数据失败");
        }
        return pushApiResult;

    }
}
